package com.lipaluma.xml.validator;

import java.util.Date;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

import org.apache.commons.lang.BooleanUtils;
import org.joda.time.format.DateTimeFormat;

import com.lipaluma.exceptions.CsvParserException;
import com.lipaluma.field.validator.ValidatorFactory;
import com.lipaluma.util.ParserUtils;

@XmlRootElement(name=XmlConstantValidator.CONSTANT)
@XmlAccessorType(XmlAccessType.FIELD)
public class XmlConstantValidator implements XmlValidator {
	public static final String CONSTANT = "constant";
	
	@XmlAttribute
	private String value;
	@XmlAttribute
	private String pattern;
	@XmlAttribute
	private Integer precision;
	
	@Override
	public String getFunctionValidation() {
		return ValidatorFactory.VALIDATION_CONSTANT_FUNCTION;
	}
	
	public String getConstantValue() {
		return value;
	}
	public String getPattern() {
		return pattern;
	}
	public Integer getPrecision() {
		return precision;
	}
	
	public <T> T getConstantValue(Class<T> clazz) {
		try {
			if(String.class.equals(clazz))
				return clazz.cast(value);
			else if(boolean.class.equals(clazz) || Boolean.class.equals(clazz))
				return clazz.cast(BooleanUtils.toBoolean(value));
			else if(short.class.equals(clazz) || Short.class.equals(clazz) ||
					int.class.equals(clazz) || Integer.class.equals(clazz) ||
					long.class.equals(clazz) || Long.class.equals(clazz))
				return clazz.cast(Long.parseLong(value));
			else if(double.class.equals(clazz) || Double.class.equals(clazz) ||
					float.class.equals(clazz) || Float.class.equals(clazz))
				return clazz.cast(Double.parseDouble(value));
			else if(Date.class.equals(clazz))
				return clazz.cast(DateTimeFormat.forPattern(pattern).parseDateTime(value).toDate());
			else if(clazz.isEnum())
				return clazz.cast(ParserUtils.parseToEnum(clazz, value));
		} catch (NumberFormatException e) {
			throw new CsvParserException("Error on constant validator on parsing the value "+value+" to class "+clazz, e);
		}
		throw new CsvParserException("Error on constant validator : the type "+clazz+" is unrecognized to cast");
	}
}
